<template>
  <basic-container>
    <el-tabs v-model="activeName" type="card" class="demo-tabs">
      <el-tab-pane label="基本信息" name="info">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="岗位序列名称" align="center">
            {{ descriptions.name }}
          </el-descriptions-item>
          <el-descriptions-item label="岗位序列编号" align="center">
            {{ descriptions.code }}
          </el-descriptions-item>
          <el-descriptions-item label="密级" align="center">
            {{ securityLabel(descriptions.security) }}
          </el-descriptions-item>
          <el-descriptions-item label="简介" align="center">
            {{ descriptions.note }}
          </el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>
      <el-tab-pane label="岗位" name="list">
        <div class="pt10">
          <el-button type="primary" icon="filter" @click="openDialog">添加岗位</el-button>
          <el-button type="info" plain icon="sort" @click="openSort">排序</el-button>
          <avue-crud
            :option="option"
            v-model:search="search"
            v-model:page="page"
            v-model="form"
            :table-loading="loading"
            :data="data"
            :before-open="beforeOpen"
            ref="crud"
            @row-update="rowUpdate"
            @row-save="rowSave"
            @row-del="rowDel"
            @search-change="searchChange"
            @search-reset="searchReset"
            @selection-change="selectionChange"
            @current-change="currentChange"
            @size-change="sizeChange"
            @refresh-change="refreshChange"
            @on-load="onLoad"
          >
            <template #security="scope">
              <div>{{ securityLabel(scope.row.security) }}</div>
            </template>
          </avue-crud>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 选择岗位弹窗 -->
    <el-dialog v-model="choosePositionDialog" width="800">
      <template #title>
        <div class="flex flex-between">
          <div class="f18">选择岗位</div>
          <div class="flex form">
            <el-input v-model="positionName" placeholder="请输入岗位名称" class="mr10"></el-input>
            <el-button type="primary" icon="search" @click="onSearch">搜索</el-button>
            <el-button type="info" plain icon="search" @click="onReset">重置</el-button>
          </div>
        </div>
      </template>

      <el-table :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="index" label="序号" width="80" />
        <el-table-column prop="name" label="岗位名称" />
        <el-table-column prop="securityLabel" label="密级" />
      </el-table>

      <div class="flex flex-center mt10">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.currentPage"
          :page-sizes="[100, 200, 300, 400]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
        >
        </el-pagination>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="choosePositionDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmChoose">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <SortDialog ref="child" :data="data" @sort="sort" />
  </basic-container>
</template>

<script>
import { getDetail as getPositionSequenceDetail } from '@/api/position/positionSequence';
import { getPositionSequenceLists } from '@/api/position/team';
import { getList as getPositionList, add, remove, update } from '@/api/position/positionInstance';
import { getDetail, sort } from '@/api/position/position';
import option from '../options/positionSequence';
import SortDialog from './sortDialog.vue';

export default {
  components: { SortDialog },
  props: {
    currentNode: Object,
  },
  watch: {
    currentNode: {
      handler(e) {
        if (e.level == 3) {
          this.getDetail();
          this.onLoad(this.page);
        }
      },
      deep: true,
    },
  },
  mounted() {
    this.option.column[3].dicData = this.website.securityLists;
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: option,
      data: [],
      activeName: 'list',
      descriptions: {},
      choosePositionDialog: false,
      tableData: [],
      chooseLists: [],
      positionName: '',
    };
  },
  computed: {},
  methods: {
    async sort(data) {
      await sort(
        data.map(item => ({
          id: item.parentId,
          sort: item.sort,
        }))
      );
      this.$message.success('已重新排序');
      this.onLoad(this.page);
      this.$emit('refresh');
    },
    openSort() {
      this.$refs.child.open();
    },
    async openDialog() {
      this.choosePositionDialog = true;
      const res = await getPositionSequenceLists({
        current: this.page.currentPage,
        size: this.page.pageSize,
        isPublished: 1,
      });
      this.page.total = res.data.data.total;
      this.tableData = res.data.data.records.map((item, index) => {
        return {
          createUser: item.createUser,
          name: item.name,
          note: item.note,
          security: String(item.security),
          securityLabel: this.securityLabel(item.security),
          code: item.code,
          id: item.id,
          statusName: item.statusName,
          index: index + 1,
        };
      });
    },
    handleSelectionChange(e) {
      this.chooseLists = e;
    },
    confirmChoose() {
      let p = [];
      this.chooseLists.forEach((list, index) => {
        let data = {
          positionSequenceId: this.currentNode.data.id,
          positionId: list.id,
        };
        p.push(add(data));
      });
      Promise.all(p)
        .then(res => {
          this.$message.success('添加成功');
          this.choosePositionDialog = false;
          this.onLoad(this.page);
          this.$emit('refresh');
        })
        .catch(err => {
          this.$message.error('添加失败');
        });
    },
    securityLabel(security) {
      let securityObj = this.website.securityLists.find(item => item.value == security);
      return securityObj ? securityObj.label : security;
    },
    getDetail() {
      getPositionSequenceDetail(this.currentNode.data.id).then(res => {
        this.descriptions = res.data.data;
      });
    },
    rowSave(row, done, loading) {
      row.sequenceId = this.currentNode.data.id;
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      const data = {
        id: row.parentId,
        countRequireTime: Number(row.countRequireTime),
      };
      update(data).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$emit('refresh');
          return remove(row.parentId);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          this.form.security = this.securityLabel(this.form.security);
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      if (this.$refs.crud) {
        this.$refs.crud.toggleSelection();
      }
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page, this.query);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page, this.query);
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (!this.currentNode.data.id) {
        return;
      }
      const { name, note, code } = this.search;
      const param = {};
      if (name) {
        param['name'] = name;
      }
      if (note) {
        param['note'] = note;
      }
      if (code) {
        param['code'] = code;
      }
      getPositionList(this.currentNode.data.id, param).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records
          .map(item => {
            return {
              ...item.position,
              parentId: item.id,
              countRequireTime: item.countRequireTime,
              sort: item.sort,
            };
          })
          .sort((a, b) => a.sort - b.sort);

        this.loading = false;
        this.selectionClear();
      });
    },
    async onSearch() {
      const res = await getPositionSequenceLists({
        name: this.positionName,
        current: this.page.currentPage,
        size: this.page.pageSize,
        isPublished: 1,
      });
      this.page.total = res.data.data.total;
      this.tableData = res.data.data.records.map((item, index) => {
        return {
          createUser: item.createUser,
          name: item.name,
          note: item.note,
          security: String(item.security),
          securityLabel: this.securityLabel(item.security),
          index: index + 1,
          code: item.code,
          id: item.id,
          statusName: item.statusName,
        };
      });
    },
    async onReset() {
      this.positionName = '';
      const res = await getPositionSequenceLists({
        current: this.page.currentPage,
        size: this.page.pageSize,
        isPublished: 1,
      });
      this.page.total = res.data.data.total;
      this.tableData = res.data.data.records.map((item, index) => {
        return {
          createUser: item.createUser,
          name: item.name,
          note: item.note,
          security: String(item.security),
          securityLabel: this.securityLabel(item.security),
          index: index + 1,
          code: item.code,
          id: item.id,
          statusName: item.statusName,
        };
      });
    },
    handleCurrentChange(e) {
      this.page.currentPage = e;
      this.openDialog();
    },
    handleSizeChange(e) {
      this.page.pageSize = e;
      this.openDialog();
    },
  },
};
</script>

<style>
.form {
  width: 50%;
  margin: 0 auto;
}
.f18 {
  font-size: 18px;
  font-weight: bold;
}
</style>
